<template>
	<div>
		<el-dialog :visible="visible" :title="title" :width="width" :show-close="false">
			<el-form ref="d-form" :model="form" :label-position="labelPosition" label-width="120px">
				<el-row>
					<el-col v-for="(item, index) in items" v-show="item.hidden ? !item.hidden(form) : true" :key="index" :span="item.span || 20">
						<el-form-item :label="item.label" :prop="item.prop" :rules="item.hidden && item.hidden(form) ? null : item.rules">
							<el-tooltip :disabled="!item.tip" effect="dark" :content="item.tip" placement="top">
								<slot v-if="item.elName === 'slot'" :name="item.prop" :form="form"></slot>
								<el-component
									v-else
									v-model="form[item.prop]"
									:el-name="item.elName"
									:on="item.on || {}"
									:attrs="item.attrs || {}"
									:options="item.options || []"
									:disabled="item.disabled ? item.disabled(form) : false"
								></el-component>
							</el-tooltip>
						</el-form-item>
					</el-col>
					<slot></slot>
				</el-row>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button size="small" @click="onCancel">取 消</el-button>
				<el-button type="primary" size="small" @click="onSubmit">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	// 验证器文档地址:https://github.com/yiminghe/async-validator
	import elComponent from './lib/elComponent.js';
	export default {
		name: 'ElDialogForm',
		components: {
			elComponent,
		},
		props: {
			// 是否显示dialog
			visible: {
				type: Boolean,
				default: false,
			},
			// 标题
			title: {
				type: String,
				default: '',
			},
			// 宽度
			width: {
				type: String,
				default: '',
			},
			// 表单项
			items: {
				type: Array,
				default: () => [],
			},
			// 表单值
			form: {
				type: Object,
				default: () => {
					return {};
				},
			},
			labelPosition: {
				type: String,
				default: 'right',
			},
		},
		methods: {
			onSubmit() {
				this.$refs['d-form'].validate((valid) => {
					if (valid) {
						this.$emit('submit', this.form);
					}
				});
			},
			onCancel() {
				this.$emit('update:visible', false);
				this.$emit('cancel');
			},
			close() {
				this.$emit('update:visible', false);
			},
		},
	};
</script>

<style>
	.el-form-item {
		margin-bottom: 15px !important;
	}
</style>
